<?php
/**
 * Controller to manage products in admin area
 * 
 * @author Konstantin Shamko <konstantin.shamko@gmail.com> 
 * @version 0.0.1
 * @copyright  Copyright (c) 2009 Konstantin Shamko
 * @package Products Module
 * @license  New BSD License
 * 
 */
class admin_ProductsController extends Bel_Controller_Aed  {
	
	/**
	 * Initialization. Creates left menu for index & form action
	 * 
	 */
	function init() {
		$this->_model = new Models_Products();
		$this->_formname = 'products_form';
		parent::init ();
		$this->_items_on_page = 25;
		$this->_grid_template = 'products/products/grid.tpl';
		
		if($this->_request->getParam('product_id') && $this->_request->getActionName()=='form'){
			Helpers_Products_Admin_ProductsMenu::leftMenu($this->_request->getParam('product_id'));
		}		
	}

	/**
	 * Displays product list. Add button is with available product templates dropdown
	 *
	 */
	public function indexAction(){
		$oTemplates = new Models_ProductTemplates();		
		$this->view->assign('templates',$oTemplates->fetchAll(null,'product_template_name'));		
		parent::indexAction();
	}
	
	/**
	 * Change _index_action to _form_action value to redirect to form after modifying product.
	 * Usability feature 
	 *
	 */
	protected function _beforeModify(){
		$this->_index_action = $this->_form_action;
	}
	
	/**
	 * Clears products cache after edit product
	 *
	 */
	protected function _afterModify(){
		if($this->_current_entry){
			Helpers_Products_Cache::clearProductCache($this->_current_entry['product_id']);
		}
	}
	
	/**
	 * Clears product cache after delete product
	 *
	 */
	protected function _afterDelete(){
		$this->_afterModify();
	}
	
	/**
	 * Adds attributes' fields from selected product template to product add/edit form
	 *
	 * @param Bel_Forms_Builder $form
	 */
	protected function _prepareForm(Bel_Forms_Builder $form){	
		$template_id = ($this->_current_entry)?$this->_current_entry['product_template_id']:$this->_request->getParam('template_id');
		$oTemplates = new Models_ProductTemplates();
		
		$attributes = $oTemplates->getAttributesByTemplate($template_id);		

		if($attributes){
			foreach($attributes as $attribute){
				$form->addElement($attribute['attribute_field_type'], 'attr['.$attribute['template_attribute_id'].']',array('label'=>$attribute['attribute_name']));
					
				if($attribute['attribute_field_type']=='select' || $attribute['attribute_field_type']=='radio'){
					$options = array();
					foreach($attribute['options'] as $option){
						$options[$option['value_value']] = $option['value_text'];
					}
					
					$form->addSubElement('attr['.$attribute['template_attribute_id'].']','options',$options);
				}
			}
		}

		$form->addElement('hidden','product_template_id',array('value'=>$template_id));
		$form->addElement('Submit','submit',array('value'=>'Submit'));	
	}
}
